package com.ytjj.quartz.utils;

import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.quartz.constants.WeixinConstants;
import com.ytjj.quartz.model.AccessToken;
import com.ytjj.quartz.model.JsapiTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @version 1.0
 *
 */
@Component
@Slf4j
public class WeixinCommenUtil {

    @Autowired
    private HttpRequestUtil httpRequestUtil;

    /**
     * 获取access_token的接口地址（GET） 限2000（次/天）
     */
    private static String url = WeixinConstants.ACCESS_TOKEN_URL;

    public AccessToken getToken(String appid, String appsecret) {

        AccessToken token = null;
        //访问微信服务器的地址
        String requestUrl = url.replace("APPID", appid)
                .replace("APPSECRET", appsecret);
        //创建一个json对象
        JSONObject json = httpRequestUtil.httpsRequest(requestUrl, "GET", null);
        log.info("获取到的json格式的Token为:" + json);
        //判断json是否为空
        if (json != null) {

            try {
                token = new AccessToken();
                //将获取的access_token放入accessToken对象中
                token.setAccess_token(json.getString("access_token"));
                //将获取的expires_in时间放入accessToken对象中
                token.setExpires_in(json.getInt("expires_in"));
            } catch (Exception e) {
                token = null;
                e.printStackTrace();
                log.error("系统异常！",e);
            }
        } else {
            token = null;
            // 获取token失败
            log.error("获取token失败 errcode:{} errmsg:{}");
        }
        if (token == null){
            FeiShuUtil.sendMsg("定时任务刷新微信小程序token失败,请检查");
        }
        return token;

    }


    /**
     * 获取access_token的接口地址（GET） 限2000（次/天）
     */
    private static String JSAPI_TICKET_URL = WeixinConstants.JSAPI_TICKET_URL;

    public JsapiTicket getJsapiTicket(String accessToken) {
        JsapiTicket ticket = null;

        //访问微信服务器的地址
        String requestUrl = JSAPI_TICKET_URL.replace("ACCESS_TOKEN", accessToken);
        //创建一个json对象
        JSONObject json = httpRequestUtil.httpsRequest(requestUrl, "GET", null);
        log.info("获取到的json格式的Token为:" + json);
        //判断json是否为空
        if (json != null) {
            try {
                ticket = new JsapiTicket();
                ticket.setTicket(json.getString("ticket"));
            } catch (Exception e) {
                ticket = null;
                //e.printStackTrace();
                log.error("系统异常！",e);
            }
        } else {
            ticket = null;
            // 获取token失败
            log.error("获取ticket失败 errcode:{} errmsg:{}");
        }
        return ticket;

    }
}